package com.xindaoapp.happypet.activity;

import java.util.ArrayList;
import java.util.Collections;
import java.util.List;

import android.content.Intent;
import android.graphics.Bitmap;
import android.graphics.Color;
import android.graphics.drawable.PaintDrawable;
import android.os.Bundle;
import android.util.DisplayMetrics;
import android.view.Gravity;
import android.view.LayoutInflater;
import android.view.View;
import android.view.View.OnClickListener;
import android.view.ViewGroup;
import android.widget.AdapterView;
import android.widget.AdapterView.OnItemClickListener;
import android.widget.BaseAdapter;
import android.widget.GridView;
import android.widget.ImageView;
import android.widget.LinearLayout.LayoutParams;
import android.widget.ListView;
import android.widget.PopupWindow;
import android.widget.RelativeLayout;
import android.widget.TextView;
import android.widget.Toast;

import com.nostra13.universalimageloader.core.DisplayImageOptions;
import com.nostra13.universalimageloader.core.ImageLoader;
import com.nostra13.universalimageloader.core.assist.ImageScaleType;
import com.xindaoapp.happypet.R;
import com.xindaoapp.happypet.bean.PhotoAibum;
import com.xindaoapp.happypet.bean.PhotoItem;
import com.xindaoapp.happypet.ui.PostMessageActivity;
import com.xindaoapp.happypet.utils.Constants;
import com.xindaoapp.happypet.utils.PhotoManager;

/**
 * 图片选择
 * 
 * @author chenghao
 */
public class PictureListActivity extends com.xindaoapp.happypet.ui.BaseActivity implements
        OnClickListener {
    private GridView mGridView;
    private PhotoFolderAdapter myAdapter;
    private TextView bottom_title;
    private TextView selector;

    private ArrayList<String> selectedList = new ArrayList<String>();
    private int screenWidth;
    private int screenHeight;
    /** 当前选中的下标 */
    private int mSelectIndex = 0;
    private List<PhotoAibum> photoAibums;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        ImageLoader.getInstance().clearMemoryCache();
        if (getIntent().hasExtra(Constants.PARAM_PHOTO_LIST)) {
            selectedList = getIntent().getStringArrayListExtra(Constants.PARAM_PHOTO_LIST);
        }
        DisplayMetrics metric = new DisplayMetrics();
        getWindowManager().getDefaultDisplay().getMetrics(metric);
        screenWidth = metric.widthPixels;
        screenHeight = metric.heightPixels;
        initView();
        PhotoManager photoManager = new PhotoManager(this);
        photoAibums = photoManager.getPhotoAlbum();
        initDatas();
    }


    @Override
    protected int getContentViewResId() {
        return R.layout.picture_list_layout;
    }

    private void initView() {
        mGridView = (GridView) findViewById(R.id.gridview);
        mGridView.setOnItemClickListener(mOnItemClickListener);
        bottom_title = (TextView) findViewById(R.id.bottom_title);
        bottom_title.setOnClickListener(this);
        // bottom_title.getPaint().setFlags(Paint.UNDERLINE_TEXT_FLAG);
        // bottom_title.getPaint().setAntiAlias(true);
        selector = (TextView) findViewById(R.id.selector);
        findViewById(R.id.linear_selector).setOnClickListener(this);
    }

    private void resetCounts() {
        bottom_title.setText(String.format("完成(%s/%s)", selectedList.size(),
                Constants.PUBLISHPOSTS_COUNTS));
    }

    private void initDatas() {
        if (null == photoAibums || photoAibums.size() == 0) {
            return;
        }
        ArrayList<PhotoItem> list = photoAibums.get(mSelectIndex).bitList;
        Collections.reverse(list);

        selector.setText(photoAibums.get(mSelectIndex).name);
        for (int i = 0; i < list.size(); i++) {
            if (selectedList.contains(list.get(i).imageFilePath)) {
                list.get(i).select = true;
            }
        }
        myAdapter = new PhotoFolderAdapter(list);
        mGridView.setAdapter(myAdapter);
    }

    private final OnItemClickListener mOnItemClickListener = new OnItemClickListener() {

        @Override
        public void onItemClick(AdapterView<?> arg0, View arg1, int position, long arg3) {
            PhotoItem info = (PhotoItem) (arg0.getAdapter().getItem(position));
            if (info.select) {
                info.select = !info.select;
                selectedList.remove(info.imageFilePath);
                setViewVisiable(arg1, info.select);
            } else {
                if (selectedList.size() < Constants.PUBLISHPOSTS_COUNTS) {
                    info.select = !info.select;
                    selectedList.add(info.imageFilePath);
                    // newSelectedList.add(info.imageFilePath);
                    setViewVisiable(arg1, info.select);
                } else {
                    Toast.makeText(
                            getBaseContext(),
                            String.format("已选%s张，共可选%s张", selectedList.size(),
                                    Constants.PUBLISHPOSTS_COUNTS), Toast.LENGTH_SHORT).show();
                }
            }
            resetCounts();
        }

        private void setViewVisiable(View arg1, boolean vis) {
            if (vis) {
                ((ViewHolder) arg1.getTag()).checkBox.setVisibility(View.VISIBLE);
            } else {
                ((ViewHolder) arg1.getTag()).checkBox.setVisibility(View.GONE);
            }
        }

    };

    private PopupWindow pwMyPopWindow;// popupwindow

    private void showPhotoFolder() {
        if (null == pwMyPopWindow) {
            View view = View.inflate(PictureListActivity.this, R.layout.layout_photofolder, null);
            pwMyPopWindow =
                    new PopupWindow(LayoutParams.MATCH_PARENT, (int) (screenHeight * 3.0 / 5));
            ListView lvPopupList = (ListView) view.findViewById(R.id.listview);
            lvPopupList.setAdapter(new PhotoFolder(photoAibums));
            lvPopupList.setOnItemClickListener(new OnItemClickListener() {

                @Override
                public void onItemClick(AdapterView<?> parent, View view, int position, long id) {
                    // 切换
                    mSelectIndex = position;
                    initDatas();
                    pwMyPopWindow.dismiss();
                }
            });

            // 控制popupwindow点击屏幕其他地方消失
            pwMyPopWindow.setBackgroundDrawable(new PaintDrawable(Color.TRANSPARENT));// 设置背景图片，不能在布局中设置，要通过代码来设置
            pwMyPopWindow.setOutsideTouchable(true);// 触摸popupwindow外部，popupwindow消失。这个要求你的popupwindow要有背景图片才可以成功，如上
            // pwMyPopWindow.setAnimationStyle(R.style.PopupAnimation);
            pwMyPopWindow.setContentView(view);
        }
        RelativeLayout bottom = (RelativeLayout) findViewById(R.id.bottom);
        int[] location = new int[2];
        bottom.getLocationOnScreen(location);
        pwMyPopWindow.setFocusable(true);// 加上这个popupwindow中的ListView才可以接收点击事件
        pwMyPopWindow.showAtLocation(bottom, Gravity.NO_GRAVITY, location[0], location[1]
                - pwMyPopWindow.getHeight());
    }

    class PhotoFolder extends BaseAdapter {
        private final List<PhotoAibum> list;

        public PhotoFolder(List<PhotoAibum> list) {
            super();
            this.list = list;
        }

        @Override
        public int getCount() {
            return list.size();
        }

        @Override
        public Object getItem(int position) {
            return list.get(position);
        }

        @Override
        public long getItemId(int position) {
            return 0;
        }

        @Override
        public View getView(int position, View convertView, ViewGroup parent) {
            ViewHolder holder = null;
            if (convertView == null) {
                convertView =
                        LayoutInflater.from(getBaseContext()).inflate(R.layout.item_photo_folder,
                                null);
                holder = new ViewHolder();
                holder.icon = (ImageView) convertView.findViewById(R.id.icon);
                holder.name = (TextView) convertView.findViewById(R.id.name);
                holder.count = (TextView) convertView.findViewById(R.id.count);
                convertView.setTag(holder);
            } else {
                holder = (ViewHolder) convertView.getTag();
            }
            PhotoAibum info = list.get(position);
            ImageLoader.getInstance().displayImage("file://" + info.imageFilePath, holder.icon);
            holder.name.setText(info.name);
            if (info.count == -1) {
                holder.count.setVisibility(View.GONE);
            } else {
                holder.count.setVisibility(View.VISIBLE);
            }
            holder.count.setText(String.valueOf(info.count));
            return convertView;
        }

        class ViewHolder {
            ImageView icon;
            TextView name;
            TextView count;
        }

    }


    class PhotoFolderAdapter extends BaseAdapter {
        private ArrayList<PhotoItem> list = new ArrayList<PhotoItem>();
        DisplayImageOptions defaultOptions;

        public PhotoFolderAdapter(ArrayList<PhotoItem> list) {
            super();
            defaultOptions =
                    new DisplayImageOptions.Builder()
                            .resetViewBeforeLoading(true)
                            .imageScaleType(ImageScaleType.EXACTLY_STRETCHED)
                            // .displayer(new FadeInBitmapDisplayer(1000))
                            .bitmapConfig(Bitmap.Config.RGB_565)
                            .showImageForEmptyUri(R.drawable.picture_loading)
                            .showImageOnFail(R.drawable.picture_loading)
                            .showStubImage(R.drawable.picture_loading).cacheInMemory(true)
                            .cacheOnDisc(false).build();

            this.list = list;
        }

        @Override
        public int getCount() {
            return list.size();
        }

        @Override
        public Object getItem(int position) {
            return list.get(position);
        }

        @Override
        public long getItemId(int position) {
            return 0;
        }

        @Override
        public View getView(final int position, View convertView, ViewGroup parent) {
            ViewHolder holder = null;
            if (convertView == null) {
                convertView =
                        LayoutInflater.from(getBaseContext()).inflate(R.layout.photoalbum_item,
                                null);
                holder = new ViewHolder();
                holder.icon = (ImageView) convertView.findViewById(R.id.photoalbum_item_image);
                holder.checkBox = convertView.findViewById(R.id.checkbox);
                convertView.setTag(holder);
            } else {
                holder = (ViewHolder) convertView.getTag();
            }
            final PhotoItem info = list.get(position);
            ImageLoader.getInstance().displayImage("file://" + info.imageFilePath, holder.icon,
                    defaultOptions);
            android.widget.RelativeLayout.LayoutParams lp =
                    new android.widget.RelativeLayout.LayoutParams(screenWidth / 3, screenWidth / 3);
            holder.icon.setLayoutParams(lp);

            if (info.select) {
                holder.checkBox.setVisibility(View.VISIBLE);
            } else {
                holder.checkBox.setVisibility(View.GONE);
            }
            return convertView;
        }
    }

    class ViewHolder {
        ImageView icon;
        View checkBox;
    }

    @Override
    protected OnClickListener getLeftViewClickListener() {
        return new OnClickListener() {

            @Override
            public void onClick(View arg0) {
                finish();
            }
        };
    }

    @Override
    protected int getTopBarLeftImageViewRes() {
        return R.drawable.top_bar_back;
    }

    @Override
    protected String getTopBarTitleStrRes() {
        return "相机胶卷";
    }

    @Override
    public void onClick(View arg0) {
        switch (arg0.getId()) {
            case R.id.linear_selector:
                showPhotoFolder();
                break;
            case R.id.bottom_title:// 保存图片
                if (getIntent().getBooleanExtra(Constants.KEY_SELECT_PICTURE_MODE, false)) {
                    if (selectedList.size() > 0) {
                        Intent data = new Intent(getBaseContext(), PostMessageActivity.class);
                        data.putStringArrayListExtra(Constants.PARAM_PHOTO_LIST, selectedList);
                        if (getIntent().hasExtra(Constants.KEY_SHAITUINFO)) {
                            data.putExtra(Constants.KEY_SHAITUINFO, getIntent()
                                    .getSerializableExtra(Constants.KEY_SHAITUINFO));
                        }
                        startActivity(data);
                        finish();
                    } else {
                        Toast.makeText(getBaseContext(), "请先选择图片！", Toast.LENGTH_SHORT).show();
                    }
                } else {
                    Intent data = new Intent();
                    data.putStringArrayListExtra(Constants.PARAM_PHOTO_LIST, selectedList);
                    setResult(RESULT_OK, data);
                    finish();
                }
                break;
        }
    }

}
